package com.mach.platform.service;

import com.mach.platform.domain.SysImg;
import com.mach.platform.repository.SysImgRepo;
import com.mach.platform.utils.springdata.DynamicSpecifications;
import com.mach.platform.utils.springdata.SearchFilter;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 * @Description:
 * @Package: com.mach.platform.service
 * @time 2018/8/20 0020 11:58
 */
@Service
public class SysImgServiceImpl implements BaseService<SysImg> {

	@Autowired
	private SysImgRepo sysImgRepo;


	/**
	 * 保存
	 *
	 * @param sysImg 保存的实体
	 * @return T 返回保存后的实体
	 */
	@Transactional(rollbackOn = Exception.class)
	@Override
	public SysImg save (SysImg sysImg) {
		return sysImgRepo.saveAndFlush(sysImg);
	}

	/**
	 * 插入，批量保存
	 *
	 * @param list 实体集合
	 * @return List<T>
	 */
	@Override
	public List<SysImg> insertObjInBatch (List<SysImg> list) {
		return null;
	}

	/**
	 * 更新
	 *
	 * @param sysImg 跟新的实体
	 * @return T
	 */
	@Transactional(rollbackOn = Exception.class)
	@Override
	public SysImg update (SysImg sysImg) {
		return sysImgRepo.saveAndFlush(sysImg);
	}

	/**
	 * 删除--批量删除
	 *
	 * @param ids 批量删除id
	 * @return int 影响数
	 */
	@Transactional(rollbackOn = Exception.class)
	@Override
	public int delete (Long[] ids) {
		SysImg delOne = sysImgRepo.getOne(ids[0]);
		String picUrl = delOne.getImgUrl();
		// 删除 图片
		File file = new File(picUrl);
		if (file.exists()) {
			try {
				FileUtils.forceDelete(file);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sysImgRepo.deleteByIdIn(ids);
	}

	/**
	 * 获取列表数据---使用 com.mach.platform.utils.springdata  下的DynamicSpecifications 的
	 * 写法进行分页查询
	 *
	 * @param pageable 分页参数
	 * @param params   其他参数
	 * @return Page<T>
	 */
	@Override
	public Page<SysImg> list (Pageable pageable, Map params) {
		Specification specification = DynamicSpecifications
				                              .bySearchFilter(SearchFilter.parse(params).values(), SysImg.class);

		return sysImgRepo.findAll(specification, pageable);
	}

	/**
	 * 获取单体 数据
	 *
	 * @param id 获取详情的id
	 * @return T
	 */
	@Override
	public SysImg info (Long id) {
		return sysImgRepo.getById(id);
	}
}
